class Cart {
    constructor() {
        //显示用户名字
        this.getData()
        //购物车数量
        this.shopNum()
        this.axiosRes()
        //判断登录
        this.checkLogin()
        this.read()
        this.bindEve()

    }
    //响应拦截
    axiosRes() {
        // 添加响应拦截器
        axios.interceptors.response.use(function (response) {
            // 对响应数据做点什么
            // console.log(response);
            if (response.data.code == 401) {
                location.assign('./login.html?returnUrl=./cart.html')
            }
            return response;
        }, function (error) {
            // 对响应错误做点什么
            return Promise.reject(error);
        });
    }
    //顶部
    self(ele) {
        let span = document.querySelector(".allgoods span")
        span.innerHTML = ele
    }
    //判断用户是否登录
    checkLogin() {
        let token = localStorage.getItem("token");
        if (!token) location.href = './login.html'
    }
    //渲染数据
    async read() {
        let token = localStorage.getItem("token");
        axios.defaults.headers.common['Authorization'] = token;
        let userId = localStorage.getItem("user_id")
        //获取数据 状态码
        let { data, status } = await axios.get("http://localhost:8888/cart/list/?id=" + userId)
        // console.log(data);
        //如果服务器状态码不等于200  就终止运行
        if (!status == 200) return;
        // console.log(data);
        //token过期
        if (data.code == 0) {
            location.assign('./login.html?returnUrl=./cart.html');
        }
        let html = ""
        // console.log(data);
        //遍历 获取数据
        data.cart.forEach(ele => {
            // console.log(ele);
            html += `<ul class="goods-list yui3-g" data-id=${ele.goods_id}>
            <li class="yui3-u-3-8 pr">
                <input type="checkbox" class="good-checkbox">
                <div class="good-item">
                    <div class="item-img">
                        <img src=${ele.img_small_logo}>
                    </div>
                    <div class="item-msg">${ele.title}</div>
                </div>
            </li>
            <li class="yui3-u-1-8">
               
            </li>
            <li class="yui3-u-1-8">
                <span class="price">${ele.current_price}</span>
            </li>
            <li class="yui3-u-1-8">
                <div class="clearfix">
                    <a href="javascript:;" class="increment mins">-</a>
                    <input autocomplete="off" type="text" value="${ele.cart_number}" minnum="1" class="itxt">
                    <a href="javascript:;" class="increment plus">+</a>
                </div>
                <div class="youhuo">有货</div>
            </li>
            <li class="yui3-u-1-8">
                <span class="sum">${ele.current_price * ele.cart_number}</span>
            </li>
            <li class="yui3-u-1-8">
                <div class="del1">
                    <a class="delgood"  href="javascript:;">删除</a>
                </div>
                <div>移到我的关注</div>
            </li>
        </ul>
            `
        });
        this.$(".cart-list").innerHTML = html;

    }
    /* 绑定事件在这里*/
    bindEve() {
        //全选按钮点击事件
        this.$('.cart-th input').addEventListener('click', this.allCheck)
        //单个按钮  用事件委托的方式
        this.$('.cart-list').addEventListener('click', this.dispach)
        //点击关闭广告
        this.$('.close-btn').addEventListener('click', this.closeAd)

    }
    //查看  分派
    dispach = (eve) => {
        let tar = eve.target
        //判断点击单选框
        if (eve.target.classList.contains("good-checkbox")) {
            this.onePlus(eve.target)

        }
        //判断点击的是否是删除
        if (tar.classList.contains("delgood")) {
            this.delGoods(tar)
        }
        //判断点击的是否是 + -
        if (tar.classList.contains("plus") || tar.classList.contains("mins")) {
            this.modifyCount(eve)
        }


    }
    //显示购物车商品数量
    async shopNum() {
        axios.defaults.headers.common['Authorization'] = localStorage.getItem("token")
        let res = await axios.get("http://localhost:8888/cart/list/?id=" + localStorage.getItem('user_id'))
        let { data, status } = res
        console.log(data);
        let num = 0
        if (status == 200 && data.code == 1) {

            data.cart.map(v => {
                // console.log(v);
                return num += v.cart_number
            })
            // if (num < 1) num = 0
            this.$('.count').innerHTML = num
        }

    }
    //关闭广告
    closeAd = () => {
        this.$('.mobile img').style.display = "none"
        this.$('.close-btn').style.display = "none"
    }
    //发送请求 获取数据 修改名字
    async getData() {
        // console.log(this);
        axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';
        axios.defaults.headers.common['Authorization'] = localStorage.getItem("token")
        let res = await axios.get("http://localhost:8888/users/info?id=" + localStorage.getItem("user_id"))

        let { data, status } = res
        // console.log(data.info.nickname, this);
        if (status == 200 && data.code == 1) {
            this.$('.nav').firstElementChild.firstElementChild.innerHTML = "您好，尊敬的" + data.info.nickname

        }

    }
    //修改数量实现
    modifyCount(eve) {
        // console.log(tar.type);
        //判断是  点击  还是  输入  事件
        if (eve.target.type == 'checkbox') return;

        let value = 0;
        let input = "";
        if (eve.type == "click") {
            if (eve.target.innerHTML == "+") {
                input = eve.target.previousElementSibling

                value = input.value - 0 + 1

            }

            if (eve.target.innerHTML == "-") {
                input = eve.target.nextElementSibling

                value = input.value - 1

                if (value < 1) {
                    value = 1;
                }

            }
            input.value = value

        }
        if (eve.type == "input") {
        }
        this.sumPrice(value, eve.target)
    }
    //小计实现
    sumPrice(num, target) {
        // console.log(11111);
        // console.log(num, target);
        // 找到最大父级ul
        let ul = this.getFather(target)
        // console.log(ul, num);
        // 获取单价
        let price = this.getChildren(ul, '.price', "innerHTML")
        //商品id
        let goodsId = ul.dataset.id
        // 保留两位小数
        let sumprice = ul.querySelector(".sum")
        sumprice.innerHTML = (num * price).toFixed(2)
        //  调用sendCount
        this.sendCount(num, goodsId)
        // console.log(goodsId);
        // 计算总价
        this.tNum()
        // console.log(sumprice);
    }
    // 发送ajax,修改服务器商品数量
    time = ""
    sendCount(num, goodId) {

        clearTimeout(this.time)
        this.time = setTimeout(() => {
            axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded';

            axios.defaults.headers.common['Authorization'] = localStorage.getItem("token");

            let userId = localStorage.getItem("user_id");

            let parm = `id=${userId}&goodsId=${goodId}&number=${num}`

            axios.post("http://localhost:8888/cart/number", parm).then(res => {
                console.log(res, "22");

            })
        }, 300)
    }

    //删除实现
    delGoods = (tar) => {
        let _this = this
        let ul = this.getFather(tar)
        // console.log(ul);
        layer.msg('确定残忍的抛弃奴家吗?', {
            time: 20000, //20s后自动关闭
            btn: ['确定', '取消'],
            yes(index) {
                layer.close(index);
                // console.log(1111);
                // 获取商品id和用户id,删除ul
                let goodId = ul.dataset.id
                let userId = localStorage.getItem("user_id")
                let token = localStorage.getItem("token")

                //请求头携带token
                axios.defaults.headers.common['Authorization'] = token;
                axios.get("http://localhost:8888/cart/remove?id=" + userId + "&goodsId=" + goodId)
                    .then(({ data, status }) => {
                        if (status == 200 && data.code == 1) {
                            //说明请求成功 删除成功

                            ul.remove()

                            console.log(_this.getChildren(ul, ".good-checkbox", "checked"));
                            _this.getChildren(ul, ".good-checkbox", "checked") && _this.tNum()
                            _this.shopNum()

                        }
                    })
            }
        });

    }
    //递归寻找父级
    getFather(ele, tar = "ul") {
        if (ele.nodeName == tar.toUpperCase()) {
            return ele
        }
        return this.getFather(ele.parentNode)
    }
    //全选按钮实现
    allCheck = (eve) => {
        let status = eve.target.checked;
        // console.log(status);
        this.one(status)
        this.tNum()
    }
    //单个按钮
    one(status) {
        let checks = document.querySelectorAll(".good-checkbox")
        // console.log(checks);
        checks.forEach(flag => flag.checked = status)
    }
    //单个按钮 升级
    onePlus(tar) {
        // console.log(tar);
        if (tar.checked) {
            //看看下面多选按钮的状态
            let checks = document.querySelectorAll(".good-checkbox")
            let res = [...checks].some(box => !box.checked)
            if (!res) this.$('.cart-th input').checked = true;


        } else {
            this.$('.cart-th input').checked = false;
        }
        this.tNum()

    }
    //统计数量  价格
    tNum() {

        let tNumber = 0;
        let tPrice = 0;
        //把商品列表获取过来，然后遍历
        //查看多选的状态以及后面的数量和价格
        let goods = document.querySelectorAll(".goods-list")
        //遍历获取到每一个ul 就是每一个商品
        goods.forEach(ul => {

            let flag = this.getChildren(ul, ".good-checkbox", "checked")
            // console.log(flag);
            if (flag) {


                //多选按钮选中  获取后面的数量 和 价格
                let number = this.getChildren(ul, ".itxt", "value") - 0
                let price = this.getChildren(ul, ".sum", "innerHTML") - 0
                // console.log(tNumber, tPrice);
                tNumber += number;
                tPrice += price
                // console.log(tNumber, tPrice);
            }

            // console.log(this.$('.clearfix div input'));

            //给最下面更改总价  数量

            this.$(".sumprice-top strong").innerHTML = tNumber
            this.$('.summoney span').innerHTML = tPrice.toFixed(2)

            this.self(this.$(".sumprice-top strong").innerHTML)

        })


        if (goods.length == 0) {

            this.$(".sumprice-top strong").innerHTML = 0
            this.$('.summoney span').innerHTML = 0
            this.$('.allgoods span')[0].innerHTML = 0
            // console.log(this.$('.allgoods span'));
        }



    }
    //获取父节点下的某个子节点
    getChildren(father, chilr, attr = "value") {
        return father.querySelector(chilr)[attr]
    }
    //获取节点对象
    $(ele) {
        let res = document.querySelectorAll(ele)
        return res.length == 1 ? res[0] : res
    }

}
new Cart;